// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    traceUser: true,
    env: 'aaa111-9gh9fp5ieac4de5d'
})

const db = cloud.database()
const $ = db.command.aggregate

function convertDate(date) {
    var now = new Date(date)
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth(); //得到月份
        var date = now.getDate(); //得到日期
        month = month + 1;
        if (month < 10) month = "0" + month;
        if (date < 10) date = "0" + date;
        var strtime = "";
        strtime = year + "-" + month + "-" + date
        return strtime
}

// 云函数入口函数
exports.main = async (event, context) => {
    console.log(event.tripid)
    var result = {}
    //拿到行程总消费
    var all = await db.collection('accrecord').aggregate()
        .match({
            tripid: event.tripid
        })
        .group({
            _id: '$tripid',
            sumAllAmount: $.sum('$amount')
        })
        .end()
    if (all.list.length > 0) {
        result["total"] = all.list[0].sumAllAmount

        var everyDay = await db.collection('accrecord').aggregate()
            .match({
                tripid: event.tripid
            })
            .group({
                _id: '$timeStamp',
                sumDayAmount: $.sum('$amount')
            })
            .sort({
                _id: -1
            })
            .end()
        console.log(everyDay)
        var dayData = []
        for (var i = 0; i < everyDay.list.length; i++) {
            var oneDayData = {}
            oneDayData["dayTotle"] = everyDay.list[i].sumDayAmount
            oneDayData["time"] = convertDate(everyDay.list[i]._id)
            console.log(everyDay.list[i]._id)
            var dayRecords = []
            //读数据库
            await db.collection('accrecord').where({
                tripid: event.tripid,
                timeStamp: everyDay.list[i]._id
            }).get().then(res => {
                console.log(res.data)
                for (var j = 0; j < res.data.length; j++) {
                    var record = {}
                    record["name"] = res.data[j].name
                    record["note"] = res.data[j].note
                    record["recordId"] = res.data[j]._id
                    record["classifi"] = res.data[j].classifi
                    record["amount"] = res.data[j].amount
                    dayRecords.push(record)
                }
            })
            oneDayData["record"] = dayRecords
            dayData.push(oneDayData)
        }
        result["day"] = dayData
    }
    return result
}